package com.szxb.facebus.db.manager;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szxb.facebus.BusApp;
import com.szxb.facebus.db.entity.bean.PosRecord;
import com.szxb.facebus.db.entity.face.LineBlackFaceListEntityDao;
import com.szxb.facebus.db.entity.face.LineFaceRecordEntity;
import com.szxb.facebus.db.entity.face.LineFaceRecordEntityDao;
import com.szxb.facebus.db.entity.scan.BlackListEntity;
import com.szxb.facebus.db.entity.scan.BlackListEntityDao;
import com.szxb.facebus.db.entity.scan.MacKeyEntity;
import com.szxb.facebus.db.entity.scan.MacKeyEntityDao;
import com.szxb.facebus.db.entity.scan.PublicKeyEntity;
import com.szxb.facebus.db.entity.scan.PublicKeyEntityDao;
import com.szxb.facebus.db.entity.scan.ScanInfoEntity;
import com.szxb.facebus.db.entity.scan.ScanInfoEntityDao;
import com.szxb.facebus.task.work.WorkThread;
import com.szxb.facebus.util.basics.Constant;
import com.szxb.facebus.util.basics.DateUtil;
import com.szxb.facebus.util.schedule.ThreadFactory;

import org.greenrobot.greendao.query.Query;

import java.util.Calendar;
import java.util.List;

import static com.szxb.facebus.db.manager.DBCore.getDaoSession;

/**
 * 作者：Tangren on 2018-12-07
 * 包名：com.szxb.facebus.db.manager
 * 邮箱：996489865@qq.com
 * TODO:一句话描述
 */

public class DBManager {

    /**
     * @return 刷脸未上传记录
     */
    public static List<LineFaceRecordEntity> getUnLineFaceRecordList() {
        LineFaceRecordEntityDao dao = getDaoSession().getLineFaceRecordEntityDao();
        return dao.queryBuilder()
                .whereOr(LineFaceRecordEntityDao.Properties.Status.eq(1), LineFaceRecordEntityDao.Properties.Status.eq(4))
                .where(LineFaceRecordEntityDao.Properties.Time.le(DateUtil.getCurrentDateLast(Calendar.SECOND, 30)))
                .limit(10).orderDesc(LineFaceRecordEntityDao.Properties.Id).build().list();
    }

    /**
     * @param record 记录
     *               保存交易记录
     */
    public static void saveFaceRecord(PosRecord record) {
        LineFaceRecordEntity lineFaceRecordEntity = new LineFaceRecordEntity();
        lineFaceRecordEntity.setBiz_data_single(record.getBiz_data());
        lineFaceRecordEntity.setMch_trx_id(record.getMch_trx_id());
        lineFaceRecordEntity.setApp_id(BusApp.getPosManager().getAppId());
        lineFaceRecordEntity.setOpenid(record.getOpen_id());
        lineFaceRecordEntity.setPay_fee(record.getPay_fee());
        lineFaceRecordEntity.setQrcode(record.getFacedatac());
        lineFaceRecordEntity.setTime(record.getCost_time());
        ThreadFactory.getScheduledPool().execute(new WorkThread(Constant.SAVE_SCAN_FACE_RECORD, lineFaceRecordEntity));
    }

    /**
     * @param lineFaceRecordEntity 记录体
     *                             已上传
     */
    public static void updateFaceRecord(LineFaceRecordEntity lineFaceRecordEntity, int status) {
        lineFaceRecordEntity.setStatus(status);
        LineFaceRecordEntityDao lineFaceRecordEntityDao = getDaoSession().getLineFaceRecordEntityDao();
        lineFaceRecordEntityDao.update(lineFaceRecordEntity);
    }

    /**
     * @param uid 用户ID
     * @return 检查是否是黑名单
     */
    public static boolean checkFaceBlack(String uid) {
        LineBlackFaceListEntityDao dao = getDaoSession().getLineBlackFaceListEntityDao();
        return dao.queryBuilder()
                .where(LineBlackFaceListEntityDao.Properties.Card_id.eq(uid), LineBlackFaceListEntityDao.Properties.Status.notEq("20"))
                .count() > 0;
    }

    /**
     * 过滤相同二维码不能连刷(有效期内)
     * 如果存在返回true
     *
     * @param qrCode .
     * @return .
     */
    public static boolean filterSameQR(String qrCode) {
        ScanInfoEntityDao dao = getDaoSession().getScanInfoEntityDao();
        return dao.queryBuilder().where(ScanInfoEntityDao.Properties.Qrcode.eq(qrCode),
                ScanInfoEntityDao.Properties.Time.ge(DateUtil.getCurrentDateLast(Calendar.MINUTE, 5))).orderDesc()
                .count() > 0;
    }

    public static boolean filterOpenID(String open_id) {
        ScanInfoEntity unique = getDaoSession().getScanInfoEntityDao().queryBuilder().limit(1).orderDesc(ScanInfoEntityDao.Properties.Id).build().unique();
        if (unique != null) {
            if (!TextUtils.isEmpty(unique.getOpenid()))
                if (unique.getOpenid().equals(open_id)) {
                    return DateUtil.getMILLISECOND(DateUtil.getCurrentDate(), unique.getTime()) <= 6;
                }
        }
        return false;
    }

    /**
     * 是否属于黑名单
     *
     * @param openID
     * @return
     */
    public static boolean filterBlackName(String openID) {
        BlackListEntityDao dao = getDaoSession().getBlackListEntityDao();
        Query<BlackListEntity> build = dao.queryBuilder().where(BlackListEntityDao.Properties.Open_id.eq(openID),
                BlackListEntityDao.Properties.Time.ge(DateUtil.currentLong())).build();
        BlackListEntity blackEntity = build.unique();
        return blackEntity != null;
    }

    /**
     * 单票修改支付状态
     *
     * @param mch_trx_id 订单号
     * @param status     支付状态1:新订单，未支付，0:准实时扣款，2：批处理扣款成功 3：扣款失败后台处理,4：系统错误再次下次提交
     * @param result     返回码
     * @param tr_status  交易状态码
     */
    public static void updateTransInfo(String mch_trx_id, int status, String result, String tr_status) {
        ScanInfoEntityDao dao = getDaoSession().getScanInfoEntityDao();
        ScanInfoEntity entity = dao.queryBuilder().where(ScanInfoEntityDao.Properties.Mch_trx_id.eq(mch_trx_id)).build().unique();
        if (entity != null) {
            entity.setStatus(status);
            if (result != null)
                entity.setResult(result);
            if (tr_status != null)
                entity.setTr_status(tr_status);
            dao.update(entity);
        }
    }

    /**
     * 验码成功,保存数据
     *
     * @param object
     */
    public static void insert(JSONObject object, String mch_trx_id, String openID,
                              String qrCode, int pay_fee) {
        ScanInfoEntity infoEntity = new ScanInfoEntity();
        infoEntity.setStatus(1);//1表示未扣款
        infoEntity.setBiz_data_single(object.toJSONString());
        infoEntity.setMch_trx_id(mch_trx_id);
        infoEntity.setTime(DateUtil.getCurrentDate());
        infoEntity.setOpenid(openID);
        infoEntity.setQrcode(qrCode);
        infoEntity.setPay_fee(pay_fee);

        ThreadFactory.getScheduledPool().execute(new WorkThread(Constant.WECHAT, infoEntity));
    }


    /**
     * 删除过期的黑名单
     */
    private static void deleteOverDueBlackName() {
        BlackListEntityDao dao = getDaoSession().getBlackListEntityDao();
        List<BlackListEntity> list = dao.queryBuilder().where(BlackListEntityDao.Properties.Time
                .le(DateUtil.currentLong())).build().list();
        dao.deleteInTx(list);
    }

    /**
     * 更新黑名单
     *
     * @param memberList
     */
    public static void addBlackList(JSONArray memberList) {
        deleteOverDueBlackName();
        for (int i = 0; i < memberList.size(); i++) {
            JSONObject object = memberList.getJSONObject(i);
            BlackListEntity entity = new BlackListEntity();
            entity.setOpen_id(object.getString("open_id"));
            entity.setTime(object.getLong("time"));
            getDaoSession().insert(entity);
        }
    }


    /**
     * 获取mac秘钥
     *
     * @param keyId .
     * @return .
     */
    public static String getMac(String keyId) {
        MacKeyEntityDao dao = getDaoSession().getMacKeyEntityDao();
        MacKeyEntity unique = dao.queryBuilder().where(MacKeyEntityDao.Properties.Key_id.eq(keyId)).unique();
        if (unique != null)
            return unique.getPubkey();
        return "";

    }
    /***
     * 获取公钥

     * @param keyId 公钥ID
     * @return
     */
    public static String getPublicKey(String keyId) {
        PublicKeyEntityDao dao = getDaoSession().getPublicKeyEntityDao();
        PublicKeyEntity unique = dao.queryBuilder().where(PublicKeyEntityDao.Properties.Key_id.eq(keyId)).build().unique();
        if (unique != null)
            return unique.getPubkey();
        return "";
    }
}
